#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <errno.h>
int main()
{
    pid_t pid, pid2;
    int f;
    //父进程创建test.dat文件并写入012345
    f = open("test.dat", O_WRONLY | O_CREAT, 0644);
    if (f < 0)
    {
        /*文件创建失败*/
        fprintf(stderr, "parent %d create file test.dat failed.\n", getpid());
        exit(-1);
    }
    int c = write(f, "012345", 6);
    if (c != 6)
    {
        /*写入出错*/
        fprintf(stderr, "parent %d write to file test.dat failed.\n", getpid());
        exit(-1);
    }
    close(f);
    pid = fork();  //父进程派生子进程
    pid2 = fork(); //父进程派生另一个子进程
    if (pid < 0 || pid2 < 0)
    {
        /*派生失败*/
        fprintf(stderr, "fork failed!\n");
        exit(-1);
    }
    else if (pid == 0 || pid2 == 0)
    {
        /*子进程*/
        //打开文件
        // sleep(5); //休眠等待父亲创建出文件
        f = open("test.dat", O_RDONLY);
        if (f < 0)
        {
            /*文件打开失败*/
            fprintf(stderr, "child %d open file test.dat failed.\n", getpid());
            exit(-1);
        }
        char buf[2]; //开辟缓冲区
        while (read(f, buf, 1) > 0)
        {
            printf("%d read is : %s\n", getpid(), buf);
        }
        //关闭文件
        close(f);
        exit(51);
    }
    else if (pid > 0 || pid2 > 0)
    {
        /*父进程*/
        //父进程等待子进程结束
        pid_t k;
        int s;
        k = waitpid(pid2, &s, 0);                                                                  //死等pid2
        printf("parent %d waited child %d,child exit code is %d.\n", getpid(), k, WEXITSTATUS(s)); //退出码34
        k = waitpid(pid, &s, 0);                                                                   //死等pid
        printf("parent %d waited child %d,child exit code is %d.\n", getpid(), k, WEXITSTATUS(s)); //退出码51
        exit(0);                                                                                   //父进程结束
    }
}